package xyz.erupt.core.util;

import lombok.SneakyThrows;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;

/**
 * @author YuePeng
 * date 2019-01-17.
 */
public class DateUtil {

    public static final String DATE = "yyyy-MM-dd";

    public static final String DATE_TIME = "yyyy-MM-dd HH:mm:ss";

    public static String getSimpleFormatDateTime(Date date) {
        return getFormatDate(date, DATE_TIME);
    }

    public static String getSimpleFormatDate(Date date) {
        return getFormatDate(date, DATE);
    }

    public static String getFormatDate(Date date, String formatStr) {
        SimpleDateFormat sdf = new SimpleDateFormat(formatStr);
        return sdf.format(date);
    }

    @SneakyThrows
    public static Date getDate(String str) {
        if (str.length() == 10) {
            return new SimpleDateFormat(DATE).parse(str);
        } else {
            return new SimpleDateFormat(DATE_TIME).parse(str);
        }
    }

    /**
     * 扩展getDate方法，使其返回指定类型的日期对象
     *
     * @param fieldType 日期类型对象
     * @param str       日期字符串
     * @return java.util.Date
     * @author Ajian
     * @date 2022-11-30 00:01
     */
    @SneakyThrows
    public static Object getDate(String fieldType, String str) {
        if (Date.class.getSimpleName().equals(fieldType)) {
            if (str.length() == 10) {
                return new SimpleDateFormat(DATE).parse(str);
            } else {
                return new SimpleDateFormat(DATE_TIME).parse(str);
            }
        } else if (LocalDate.class.getSimpleName().equals(fieldType)) {
            if (str.length() == 10) {
                return LocalDate.parse(str, DateTimeFormatter.ofPattern(DATE));
            } else {
                return LocalDate.parse(str, DateTimeFormatter.ofPattern(DATE_TIME));
            }
        } else if (LocalDateTime.class.getSimpleName().equals(fieldType)) {
            if (str.length() == 10) {
                return LocalDateTime.parse(str, DateTimeFormatter.ofPattern(DATE));
            } else {
                return LocalDateTime.parse(str, DateTimeFormatter.ofPattern(DATE_TIME));
            }
        } else if (LocalTime.class.getSimpleName().equals(fieldType)) {
            return LocalTime.parse(str, DateTimeFormatter.ISO_LOCAL_TIME);
        }
        return new SimpleDateFormat(DATE_TIME).parse(str);
    }
}
